<template>
  <div>
    <!-- 评论列表 -->
    <van-cell>
      <van-image
        slot="icon"
        round
        width="30"
        height="30"
        style="margin-right: 10px"
        :src="cmt.aut_photo"
      />
      <span style="color: #466b9d" slot="title">{{ cmt.aut_name }}</span>
      <div slot="label">
        <p style="color: #363636">{{ cmt.content }}</p>
        <p>
          <span style="margin-right: 10px">{{
            cmt.pubdate | relativeTime
          }}</span>
          <!-- 回复按钮 -->
          <WriteReplay />
          <!-- <van-button size="mini" type="default">回复</van-button> -->
        </p>
      </div>
      <van-icon
        slot="right-icon"
        :name="cmt.is_liking ? 'like' : 'like-o'"
        :color="cmt.is_liking ? 'red' : ''"
        @click="clickZan"
      />
    </van-cell>

    <!-- 回复列表 -->
    <ReplayItem v-for="rep in replayList" :key="rep.com_id" :cmt="rep" />
  </div>
</template>

<script>
// 导入评论接口API
// 导入点赞/取消点赞API
import { addLike, disLike, getComments } from '@/api/comment'
// 导入回复按钮组件
import WriteReplay from './write-replay.vue'
// 导入回复组件
import ReplayItem from './replay-item.vue'
export default {
  name: 'CommentItem',
  props: {
    // 评论数据对象
    cmt: {
      required: true
    }
  },
  provide () {
    return {
      cmt: this.cmt,
      replayList: this.replayList
    }
  },
  components: { WriteReplay, ReplayItem },

  data () {
    return {
      // 回复列表
      replayList: [],
      // 查询参数对象
      q: {
        type: 'c', // a->查询文章的评论，c->查询评论的回复
        source: this.cmt.com_id, // 评论或回复id
        offset: null, // 分页偏移量（保存上一页最后一个评论的id）
        limit: 10 // 页容量
      }
    }
  },

  mounted () {},

  methods: {
    // 点赞
    async clickZan () {
      try {
        // 调用接口，发送请求为评论点赞/取消点赞
        console.log(this.cmt.com_id)
        //   如果已经点赞，则取消
        if (this.cmt.is_liking) {
          await disLike(this.cmt.com_id)
        } else {
          await addLike(this.cmt.com_id)
        }
        this.$toast.success('操作成功')
        // eslint-disable-next-line vue/no-mutating-props
        this.cmt.is_liking = !this.cmt.is_liking
      } catch (error) {
        this.$toast.fail('操作失败')
        console.log(error.message)
      }
    }
  },

  async created () {
    // 回复数据
    try {
      const res = await getComments(this.q)
      console.log('回复1', res)
      this.replayList.push(...res.data.data.results)
    } catch (error) {
      console.log('错误', error.target)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
